import 'dart:convert';

import 'package:event_bus/event_bus.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:mmkv/mmkv.dart';
import 'package:seedfour/app/constants.dart';
import 'package:seedfour/app/routes/app_routes.dart';

import '../../../models/user_info_entity.dart';
import '../../../services/api_service.dart';
import '../../../services/common_service.dart';
import '../../web_screen/screen_params.dart';
import 'state.dart';

class MineLogic extends GetxController {
  final MineState state = MineState();
  final apiService = Get.put(ApiService());
  final commonService = Get.put(CommonService());

  final MMKV mmkv = MMKV.defaultMMKV();

  final eventBus = EventBus();

  final agreementUrl = 'https://api.seedfour.com/res/api/v1/user/agreement';
  final privacyUrl = 'https://api.seedfour.com/res/api/v1/user/privacy';

  @override
  void onInit() {
    /// get user info
    _getUserInfo();
    _getStatistics();
    super.onInit();
  }

  void onSelectAccount(int index) {
    state.radioAccountIndex.value = index;
  }

  void onCancelSelectAccount() {
    state.radioAccountIndex.value = state.selectedAccountIndex.value;
  }

  void onConfirmSelectAccount() {
    EasyLoading.show(status: '切换账户中...', dismissOnTap: true);
    _changeRole(
        state.personalInfo.value!.companyList[state.radioAccountIndex.value]);
  }

  void onClickSetting() {
    Get.toNamed(RouteGet.settings);
  }

  void onClickBalance() {
    Get.toNamed(RouteGet.balance);
  }

  void onClickDeposit() {
    Get.toNamed(RouteGet.deposit);
  }

  void onClickFund() {
    Get.toNamed(RouteGet.fund);
  }

  void onClickTeam() {
    Get.toNamed(RouteGet.mineTeam);
  }

  void onClickIncome() {
    Get.toNamed(RouteGet.statisticsIncome);
  }

  void onClickAlloc() {
    Get.toNamed(RouteGet.statisticsAlloc);
  }

  void onClickExpense() {
    Get.toNamed(RouteGet.statisticsExpense);
  }

  void onClickInvite() {
    Get.toNamed(RouteGet.mineInvite);
  }

  void onClickAgreement() {
    Get.toNamed(RouteGet.webScreen,
        arguments: WebScreenParams(url: agreementUrl));
  }

  void onClickPrivacy() {
    Get.toNamed(RouteGet.webScreen,
        arguments: WebScreenParams(url: privacyUrl));
  }

  void _getUserInfo() {
    UserInfoEntity? userInfo =
        UserInfoEntity.fromJson(jsonDecode(mmkv.decodeString(kKeyUser)!));
    state.personalInfo.value = PersonalInfo.fromUserInfoEntity(userInfo);

    state.selectedAccountIndex.value = state.personalInfo.value!.companyList
        .indexWhere((e) => e == state.personalInfo.value!.currentCompany);
    state.radioAccountIndex.value = state.selectedAccountIndex.value;

    state.role.value = commonService.getRole();
  }

  void _changeRole(CompanyInfo currentCompany) {
    apiService
        .changeRole(currentCompany.roleType, currentCompany.uid)
        .then((value) {
      if (value != null) {
        _loginSuccess();
      } else {
        Get.snackbar('提示', '切换账户失败');
      }
    });
  }

  void _loginSuccess() {
    apiService.getUserInfo().then((value) {
      if (value != null) {
        EasyLoading.showSuccess('切换账户成功');
        _getUserInfo();
        _getStatistics();
        _publishEvent();
      }
    });
  }

  void _getStatistics() {
    apiService
        .statistics(DateTime.now().year.toString(), state.role.value)
        .then((value) {
      if (value != null) {
        state.statisticsInfo.value = value;
      } else {
        Get.snackbar('提示', '获取统计数据失败');
      }
    });
  }

  void _publishEvent() {
  }
}
